package com.ruoyi.web.util;

import org.apache.commons.collections4.CollectionUtils;

import java.math.BigDecimal;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;

/**
 * <br>
 *
 * @author chenwujie
 * @date 2021/2/11
 */
public class OptionalUtils {
    public static BigDecimal bigDecimalDefault(BigDecimal value) {
        return Optional.ofNullable(value).orElse(BigDecimal.ZERO);
    }

    public static <T> BigDecimal sum(List<T> list, Function<T, BigDecimal> getFunction) {
        if (CollectionUtils.isEmpty(list)) {
            return BigDecimal.ZERO;
        }

        return list.stream()
                .map(t -> {
                    try {
                        return bigDecimalDefault(getFunction.apply(t));
                    } catch (Exception e) {
                        return BigDecimal.ZERO;
                    }
                })
                .reduce(BigDecimal.ZERO, BigDecimal::add);
    }

}
